package dao

import (
	"context"
	"fabric-explorer/entity"
	"fabric-explorer/tools"
	"fmt"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
)

const (
	EVENT_COLLECTION_NAME = "event"
)

//插入event
func InsertEvent(event entity.Event) {
	// tools.InitDB()
	collection := tools.GetCollection(EVENT_COLLECTION_NAME)
	insertResult, err := collection.InsertOne(context.TODO(), event)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("Inserted a single document: ", insertResult.InsertedID)
}

//查询Event的List
func FindEventList(selecter bson.D) []entity.Event {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	collection := tools.GetCollection(EVENT_COLLECTION_NAME)
	cur, err := collection.Find(ctx, selecter)
	if err != nil {
		fmt.Println(err)
	}
	defer cur.Close(ctx)

	eventList := make([]entity.Event, 0)
	for cur.Next(ctx) {
		event := &entity.Event{}
		err := cur.Decode(event)
		if err != nil {
			fmt.Println(err)
		}
		eventList = append(eventList, *event)
	}
	if err := cur.Err(); err != nil {
		fmt.Println(err)
	}
	return eventList
}

//查询Event的page
func FindEventListPage(selecter bson.D, options *options.FindOptions) []entity.Event {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	collection := tools.GetCollection(EVENT_COLLECTION_NAME)
	cur, err := collection.Find(ctx, selecter, options)
	if err != nil {
		fmt.Println(err)
	}
	defer cur.Close(ctx)

	eventList := make([]entity.Event, 0)
	for cur.Next(ctx) {
		event := &entity.Event{}
		err := cur.Decode(event)
		if err != nil {
			fmt.Println(err)
		}
		eventList = append(eventList, *event)
	}
	if err := cur.Err(); err != nil {
		fmt.Println(err)
	}
	return eventList
}

//查询index
func GetEventNum(selecter bson.D) int64 {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	collection := tools.GetCollection(EVENT_COLLECTION_NAME)
	num, err := collection.CountDocuments(ctx, selecter)
	if err != nil {
		fmt.Println(err)
	}
	return num
}
